import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
var _excluded = ["className", "style"];
import { jsx as _jsx } from "react/jsx-runtime";
import { useRefFunction } from '@ant-design/pro-utils';
import { SortableContainer, SortableElement } from 'react-sortable-hoc';
import { sortData } from './index';
export function useDragSort(props) {
  var _props$dataSource = props.dataSource,
      dataSource = _props$dataSource === void 0 ? [] : _props$dataSource,
      onDragSortEnd = props.onDragSortEnd,
      dragSortKey = props.dragSortKey; // 拖拽排序相关逻辑

  var SortableItem = SortableElement(function (p) {
    return _jsx("tr", _objectSpread({}, p));
  });
  var SortContainer = SortableContainer(function (p) {
    return _jsx("tbody", _objectSpread({}, p));
  });
  /* istanbul ignore next */

  var handleSortEnd = useRefFunction(function (params) {
    /* istanbul ignore next */
    var newDataSource = sortData(params, dataSource);
    /* istanbul ignore next */

    if (newDataSource && onDragSortEnd) {
      /* istanbul ignore next */
      onDragSortEnd(newDataSource);
    }
  });
  var DraggableContainer = useRefFunction(function (p) {
    return _jsx(SortContainer, _objectSpread({
      useDragHandle: true,
      disableAutoscroll: true,
      helperClass: "row-dragging",
      onSortEnd: handleSortEnd
    }, p));
  });
  var DraggableBodyRow = useRefFunction(function (p) {
    var DraggableBodyRowClassName = p.className,
        DraggableBodyRowStyle = p.style,
        restProps = _objectWithoutProperties(p, _excluded); // function findIndex base on Table rowKey props and should always be a right array index


    var index = dataSource.findIndex(function (item) {
      var _props$rowKey;

      return item[(_props$rowKey = props.rowKey) !== null && _props$rowKey !== void 0 ? _props$rowKey : 'index'] === restProps['data-row-key'];
    });
    return _jsx(SortableItem, _objectSpread({
      index: index
    }, restProps));
  });
  var components = props.components || {};

  if (dragSortKey) {
    var _props$components;

    components.body = _objectSpread(_objectSpread({}, ((_props$components = props.components) === null || _props$components === void 0 ? void 0 : _props$components.body) || {}), {}, {
      wrapper: DraggableContainer,
      row: DraggableBodyRow
    });
  }

  return {
    components: components
  };
}